<?php

namespace app\common\service;

use app\common\exception\BackErrorException;
use app\common\model\Topic as TopicModel;
use app\common\model\Topic;
use app\common\model\VideoList as VideoListModel;
use app\common\model\Category as CategoryModel;
use think\Collection;
use think\facade\Db;

class TopicService extends BaseServices
{
    /**
     * 专栏首页列表
     * @param $page
     * @param $pageSize
     * @param $searchField
     * @param $searchValue
     * @param $status
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function topicIndex($page, $pageSize, $searchField, $searchValue, $status)
    {
        $list = [];
        $start = ($page - 1) * $pageSize;
        $where['is_delete'] = $status;
        $model =  TopicModel::where($where);
        $this->formatLikeSearch($model, $searchField, $searchValue);
        $count = $model->count();
        if ($count) {
            $list = $model->order('update_time', 'desc')->limit($start, $pageSize)->select();
            $list = Collection::make($list)->toArray();
            $categoryIds = array_column($list, 'category_id');
            $categoryInfo = Db::table("category")->whereIn("id", $categoryIds)->column("id,name", "id");
            foreach ($list as $key => $val) {
                $list[$key]['categoryInfo'] = $categoryInfo[$val['category_id']] ?? [];
            }
        }
        return ['total' => $count, 'list' => $list];
    }

    public function getList($page, $pageSize, $where, $order = 'id')
    {
        $start = ($page - 1) * $pageSize;
        $count = TopicModel::where($where)->count();
        $list = TopicModel::where($where)->order($order, 'desc')->limit($start, $pageSize)->select();
        $categoryIds = [];
        foreach ($list as $key => $val) {
            array_push($categoryIds, $val['category_id']);
        }
        $res = Db::table("category")->whereIn("id", $categoryIds)->column("id,name", "id");
        foreach ($list as $key => $val) {
            $list[$key]['categoryInfo'] = empty($res[$val['category_id']]) ? [] : $res[$val['category_id']];
        }
        return ['total' => $count, 'list' => $list];
    }

    public function create($data)
    {
        $category = CategoryModel::where(['id' => $data['category_id']])->find();
        $data['parent_category_id'] = $category['parent_id'];
        return TopicModel::create($data);
    }

    public function update($data, $id)
    {
        return TopicModel::update($data, ['id' => $id]);
    }

    /**
     * 上架专栏
     * @param $id
     * @return bool
     * @throws BackErrorException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function shelvesTopic($id)
    {
        $exists = TopicModel::where(['id' => $id])->find();
        if (empty($exists) || !$exists) {
            throw new BackErrorException("该专栏不存在，请检查~");
        }
        if (!TopicModel::update(['is_delete' => $this->noDelete], ['id' => $id])) {
            throw new BackErrorException("上架专栏失败");
        }
        return true;
    }

    /**
     * 下架专栏
     * @param $id
     * @throws BackErrorException
     * @version 1.0.0 解绑所有关联视频后，删除该专栏
     */
    public function remove($id)
    {
        $videos = VideoListModel::where(['topic_id' => $id])->column('id');
        if ($videos) {
            foreach ($videos as $id) {
                VideoListModel::update(['topic_id' => 0], ['id' => $id]);
            }
        }
        TopicModel::update(['is_delete' => $this->isDelete], ['id' => $id]);
    }

    public function getOne($id)
    {
        return TopicModel::where(['id' => $id])->find();
    }
}